package com.wdc.deliveryrobot.fragment;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sirui.selfstudysdk.main.SelfChassisState;
import com.wdc.deliveryrobot.R;
import com.wdc.deliveryrobot.activity.BaseActivity;
import com.wdc.deliveryrobot.activity.DeliveryActivity;
import com.wdc.deliveryrobot.activity.RunActivity;
import com.wdc.deliveryrobot.activity.TaskActivity;
import com.wdc.deliveryrobot.adapter.LocationAdapter;
import com.wdc.deliveryrobot.constant.Constants;
import com.wdc.deliveryrobot.dialog.HintDialog;

import java.nio.file.LinkOption;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class DeliveryFragment extends Fragment implements View.OnClickListener,LocationAdapter.OnItemClickListener{

    private EditText editTextOne,editTextTwo,editTextThree,editTextFour;

    private EditText lastClickedEditText;



    private RecyclerView pointRecyclerView;

    private SelfChassisState selfChassisState;

    private Button buttonStart,buttonTest;
    private String selectedPoint;

    private List<String> locations;

    private LocationAdapter adapter;

    private LinearLayout linearLayoutExit;

    private JSONArray jsonArrayPoint;
    private String point = null;

    private int select = -1;

    private int k = 0;

    private static String TAG = "deliveryFragment";

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // 加载 Fragment 的布局
        View view = inflater.inflate(R.layout.fragment_delivery, container, false);

        init(view);

        // 设置 GridLayoutManager，2 列
        GridLayoutManager gridLayoutManager = new GridLayoutManager(getContext(), 4);
        pointRecyclerView.setLayoutManager(gridLayoutManager);
        // 获取地图点位进行显示
        JSONObject jsonObjectStations = selfChassisState.getStations();
        jsonArrayPoint = jsonObjectStations.getJSONArray("point");

        Log.d(TAG,"数据点位:" + jsonArrayPoint);
        locations = new ArrayList<>();
        locations = Arrays.asList("点位1","点位2");
        if (jsonArrayPoint != null){
            locations = new ArrayList<>();
            for (int i = jsonArrayPoint.size() - 1;i >= 0;i --){
                if (!jsonArrayPoint.getJSONObject(i).getString("mapName").equals(selfChassisState.getMapName())){
                    jsonArrayPoint.remove(i);
                }else {
                    String name = jsonArrayPoint.getJSONObject(i).getString("name");
                    Log.d(TAG,"名称:" + name);
                    if (!name.equals("回收点") && !name.equals("返航点") && !name.equals("出品点"))
                        locations.add(name);
                }
            }
        }
        Log.d(TAG,"地图点位:" + locations);
        adapter = new LocationAdapter(locations, this);
        pointRecyclerView.setAdapter(adapter);

        return view;
    }

    public void init(View view){

        editTextOne = view.findViewById(R.id.lowOne);
        editTextTwo = view.findViewById(R.id.lowTwo);
        editTextThree = view.findViewById(R.id.lowThree);
        editTextFour = view.findViewById(R.id.lowFour);
        buttonStart = view.findViewById(R.id.start);
        pointRecyclerView = view.findViewById(R.id.pointRecyclerView);
        linearLayoutExit = view.findViewById(R.id.return_back);
        //移动测试
        buttonTest = view.findViewById(R.id.runPoint);
        pointRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        buttonStart.setOnClickListener(this);
        linearLayoutExit.setOnClickListener(this);
        setClickListener(editTextOne);
        setClickListener(editTextTwo);
        setClickListener(editTextThree);
        setClickListener(editTextFour);

        buttonTest.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (point == null){
                    Toast.makeText(getContext(),"请选择移动测试点位",Toast.LENGTH_SHORT).show();
                }else if (selfChassisState.isStop()){
                    Toast.makeText(getContext(),"请松开急停",Toast.LENGTH_SHORT).show();
                }else{
                    if (jsonArrayPoint != null){
                        for (int i = 0;i < jsonArrayPoint.size();i ++){
                            if (jsonArrayPoint.getJSONObject(i).get("name").equals(point)){
                                //当前点位
                                selfChassisState.linePatrolNaxvigation(Float.parseFloat(jsonArrayPoint.getJSONObject(i).get("x").toString()),Float.parseFloat(jsonArrayPoint.getJSONObject(i).get("y").toString()),Float.parseFloat(jsonArrayPoint.getJSONObject(i).get("yaw").toString()));
                                //出发判断
                                while (true){
                                    //状态等于0开始出发
                                    if (selfChassisState.getResult() == 0)
                                        break;
                                    try {
                                        Thread.sleep(1000);
                                    } catch (InterruptedException e) {
                                        throw new RuntimeException(e);
                                    }
                                }
                                Log.d("thd_","我开始出发了");

                                Intent intent = new Intent(getActivity(),RunActivity.class);
                                intent.putExtra("imageResource", R.drawable.loading);
                                startActivity(intent);

                                break;
                            }
                        }
                    }else {
                        Toast.makeText(getContext(),"请选择移动测试点位",Toast.LENGTH_SHORT).show();
                        selfChassisState.getResult();
                    }
                }

           }
        });
    }
    @Override
    public void onClick(View view) {

        switch (view.getId()){
            case R.id.start:
                //获取左边的点位信息
                boolean isSet = false;
                ArrayList<String> values = new ArrayList<>();
                // 检查每个 EditText 的内容，去除空格后，如果不为空则添加到 ArrayList
                if (!editTextOne.getText().toString().trim().isEmpty()) {
                    values.add(editTextOne.getText().toString().trim());
                    isSet = true;
                }else {
                    values.add(null);
                }
                if (!editTextTwo.getText().toString().trim().isEmpty()) {
                    values.add(editTextTwo.getText().toString().trim());
                    isSet = true;
                }else {
                    values.add(null);
                }
                if (!editTextThree.getText().toString().trim().isEmpty()) {
                    values.add(editTextThree.getText().toString().trim());
                    isSet = true;
                }else {
                    values.add(null);
                }
                if (!editTextFour.getText().toString().trim().isEmpty()) {
                    values.add(editTextFour.getText().toString().trim());
                    isSet = true;
                }else {
                    values.add(null);
                }
                if (!isSet) {
                    Toast.makeText(getActivity(),"请选择点位",Toast.LENGTH_SHORT).show();
                } else {
                    HintDialog hintDialog = new HintDialog(getContext());
                    hintDialog.setMessage(getString(R.string.start_now));
                    hintDialog.setOkButtonClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            if (selfChassisState.isStop()) {
                                Toast.makeText(getContext(), "请松开急停", Toast.LENGTH_SHORT).show();
                                return;
                            }
                            Constants.TASK_NOW = 1;

                            Intent intent = new Intent(getContext(), TaskActivity.class);
                            Constants.SEND_POINT = values;
                            for (String k : values){
                                if (k != null){
                                    Constants.SEND_NOW_POINT = k;
                                    break;
                                }
                            }
                            startActivity(intent);

                        }
                    });
                    hintDialog.setCancelButtonClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            hintDialog.dismiss();

                        }
                    });
                    hintDialog.show();
                }

                break;
            case R.id.return_back:
                if (getActivity() != null) {
                    ((DeliveryActivity) getActivity()).switchToFragment(); // 调用Activity方法切换回第一个Fragment
                }
                break;
        }

    }

    private void setClickListener(final EditText editText) {
        editText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //刷新右边按钮
                updateData();
                // 恢复上一个点击的 EditText
                if (lastClickedEditText != null) {
                    lastClickedEditText.setHintTextColor(Color.GRAY);

                    if (!TextUtils.isEmpty(lastClickedEditText.getText().toString())){
                        lastClickedEditText.setTextColor(Color.BLACK);
                    }
                    Log.d("thd_",lastClickedEditText.getText().toString());
                }
                //如果当前点击的已经有选中的，就清空选中的数据重新设置hint
                if (editText != null && !TextUtils.isEmpty(editText.getText().toString())){
                    editText.setText("");
                    editText.setHint(getString(R.string.selectPoint));
                }
                // 高亮当前点击的 EditText
                editText.setHintTextColor(Color.YELLOW); // 高亮颜色

                lastClickedEditText = editText; // 更新最后点击的 EditText

            }
        });
    }

    private void highlightEditText(EditText editText) {
        editText.setHintTextColor(Color.BLUE);

    }

    private void resetEditText(EditText editText) {
        editText.setHintTextColor(Integer.parseInt(String.valueOf(R.color.dark_gray)));
    }

    @Override
    public void onItemClick(String location) {
        if (lastClickedEditText != null) {
            lastClickedEditText.setText(location);
            lastClickedEditText.setTextColor(Color.BLACK);
        }
        point = location;
    }

    public void updateData() {
        adapter.notifyData(); // 更新适配器中的数据
    }



    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        if (context instanceof BaseActivity) {
            selfChassisState = ((BaseActivity) context).selfChassisState;
        }
    }


}